<?php
namespace App\Service\Activity;


use App\Model\Member;
use App\Model\Prize;
use App\Model\Follow;
use App\Model\Like;
use App\Model\Record;
use App\Service\BaseService;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;
use App\Model\Activity;
use App\Model\Imgs;

class ActivityService extends BaseService
{


    public function __construct($modelName = null)
    {
        parent::__construct('Activity');
    }

    /**
     * 分页获取活动列表数据(方法重写)
     * @param  array   $where    [数据条件]
     * @param  string  $orderBy  [排序字段]
     * @param  string  $order    [排序类型]
     * @param  boolean $is_page  [是否分页]
     * @param  integer $pageSize [每页显示的数量]
     * @return [obj]            [模型列表实例]
     */
    public function getAllList($where = [],$orderBy='created_at',$order='desc',$is_page=true,$pageSize = 10)
    {
        $select = $this->model->withCount('members');
        if ($where) {
            $select = $select->where($where);
        }
        $select = $select->orderBy($orderBy,$order);
        if ($is_page) {
            $list = $select->paginate($pageSize);
        }else {
            $list= $select->all();
        }
        return $list;
    }

    /**
     * 参加活动
     * @author 张永辉 2018年11月5日
     */
    public function attendActivity()
    {
        $img_ids = implode(',', $this->img_ids);
        //修改参加等活动
        if (!empty($this->id)) {
            Record::where('id', $this->id)->update(['img_ids' => $img_ids]);
            return $this->getReturn();
        }

        $insertData = [
            'activity_id' => $this->activity_id,
            'member_id'   => $this->mid,
            'desc'        => $this->desc,
            'img_ids'     => $img_ids,
        ];
        Record::insertGetId($insertData);
        return $this->getReturn();
    }

    /**
     * 参加活动的单个信息
     * @author 张永辉 2018年11月5日
     */
    public function getRecord()
    {
        $where      = [
            'activity_id' => $this->activity_id,
            'member_id'   => $this->mid,
        ];
        $this->data = Activity::where($where)->first();
        if (!$this->data) {
            return $this->getReturn();
        }
        $this->data              = $this->data->toArray();
        $imgIds                  = explode(',', $this->data['img_ids']);
        $this->data['imageData'] = Imgs::select(['id', 'name', 'cdn_path'])->find($imgIds);
        return $this->getReturn();
    }


    /**
     * 参加活动的单个信息
     * @author 张永辉 2018年11月5日
     */
    public function recommend()
    {
        $rids       = [1, 2];
        $recodeData = Record::with(['member'])->find($rids)->toArray();
        $imgIds     = array_column($recodeData, 'img_ids');
        $imgIds     = explode(',', implode(',', $imgIds));
        $imgData    = Imgs::select(['id', 'name', 'cdn_path', 'img_size'])->find($imgIds);
        if ($imgData) {
            $imgData = $imgData->toArray();
            $imgData = $this->dealKey($imgData);
        }
        $myLike   = $this->myLikeById($rids);
        $myFollow = $this->myFollow(array_column($recodeData, 'member_id'));
        foreach ($recodeData as &$item) {
            $tmp = explode(',', $item['img_ids']);
            foreach ($tmp as $key => $val) {
                $tmp[$key] = $imgData[$val]??[];
            }
            $item['imgData'] = $tmp;
            //判断是否是我的作品
            $item['member_id'] == $this->mid ? $item['isMy'] = 1 : $item['isMy'] = 0;
            in_array($item['id'], $myLike) ? $item['isLike'] = 1 : $item['isLike'] = 0;
            in_array($item['member_id'], $myFollow) ? $item['isFollow'] = 1 : $item['isFollow'] = 0;
        }
        return $recodeData;

    }

    /**
     * 获取我喜欢的记录
     * @author 张永辉 2018年11月5日
     */
    public function myLikeById($rid)
    {
        $data = Like::where('member_id', $this->mid)->whereIn('record_id', $rid)->get(['record_id'])->toArray();
        return array_column($data, 'record_id');
    }

    /**
     * 我关注的
     * @author 张永辉 2018年11月5日
     */
    public function myFollow($mids)
    {
        $data = Follow::where('follower_id', $this->mid)->whereIn('member_id', $mids)->get(['member_id'])->toArray();
        return array_column($data, 'member_id');
    }

    /**
     * 获取各个池子的数据
     * @author 张永辉 2018年11月5日
     */
    public function getData()
    {
        $data['recommend']  = $this->recommendKey();
        $data['new']        = $this->newKey();
        $data['read']       = $this->readKey();
        $data['highPraise'] = $this->highPraiseKey();
        $data['newest']     = $this->newestKey();
        $recommend          = Redis::SDIFF([$data['recommend'], $data['read']]);
        $new                = Redis::SDIFF([$data['new'], $data['read']]);
        $highPraise         = Redis::SDIFF([$data['highPraise'], $data['read']]);
        $newest             = Redis::SDIFF([$data['newest'], $data['read']]);

        $num = [10,5,5];
        $ids = array_rand($recommend,$num[0]);
        if (count($ids)<$num[0]){
            $num[1] += ($num[0]-count($ids));
        }

    }

    /**
     * 获取推荐池key
     * @author 张永辉 2018年11月5日
     */
    public function recommendKey()
    {
        return 'activity:recommend:' . $this->activity_id;
    }

    /**
     * 获取新池key
     * @author 张永辉 2018年11月5日
     */
    public function newKey()
    {
        return 'activity:new:' . $this->activity_id;
    }

    /**
     * 获取新池key
     * @author 张永辉 2018年11月5日
     */
    public function readKey()
    {

        return 'activity:read:' . $this->mid . ':' . $this->activity_id;
    }

    /**
     * 获取高赞
     * @author 张永辉 2018年11月5日
     */
    public function highPraiseKey()
    {
        return 'activity:high_praise:' . $this->activity_id;
    }

    /**
     * 获取高赞
     * @author 张永辉 2018年11月5日
     */
    public function newestKey()
    {
        return 'activity:newest:' . $this->activity_id;
    }

    /**
     * 获取单个活动
     * @author 张永辉 2018年11月5日
     */
    public function getActivityById()
    {
        $activity = Activity::with(['sponsors'])->find($this->activity_id);
        if (!$activity) {
            $this->errCode = '10003';
            $this->errMsg  = '活动不存在';
            return $this->getReturn();
        }
        $activity            = $activity->toArray();
        $activity['imgData'] = Imgs::find(explode(',', $activity['imgs_ids']));
        if ($activity['imgData']) {
            $activity['imgData'] = $activity['imgData']->toArray();
        }
        $activity['prize_ids'] = explode(',',$activity['prize_ids']);
        $activity['prize'] = Prize::whereIn('id',$activity['prize_ids'])->get()->toArray();
        foreach ($activity['prize'] as &$val){
            $val['imgs_ids'] = explode(',',$val['imgs_ids']);
        }

        return $activity;
    }


    /**
     * 获取首页信息
     * @return mixed
     * @author: 梅杰 20181106
     */
    public function getPage()
    {
        $data = Activity::select(['id','title','status','imgs_ids'])->with([
            'winner' => function($query) {
                $query->select(['member.id','nickname','headimgurl','fan_count','be_liked_count','prize_id'])->whereNotNull('prize_id');
            }
        ])->orderBy('created_at','asc')->paginate(10);

        foreach ($data as &$datum) {
            if (!empty($datum->winner[0])) {
                $datum->winner = $datum->winner[0];
                $datum->winner->prize = Prize::select('name')->find( $datum->winner->prize_id);
            }
        }
        return $data;
    }
}